package com.darren.euc.service.impl;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.darren.euc.dao.RoleDao;
import com.darren.euc.entity.PageBean;
import com.darren.euc.entity.Role;
import com.darren.euc.service.RoleService;
import com.darren.euc.util.StringUtil;

import net.sf.json.JSONObject;


@Service
public class RoleServiceImpl  implements RoleService {
	
	@Autowired
    private RoleDao roleDao;
	
    @Override
    public Role save(Role role) {    	
        return roleDao.save(role);
    }
    
    @Override
    public Role update(Role role) {   
    	roleDao.deleteRoleFunctionByRoleId(role.getId());
        return roleDao.update(role);
    }
    
    
	@Override
	public List<Role> getAll() {
		return roleDao.getAll();
	}
	
	@Override
	public List<Role> getRoleType() {
		return roleDao.getRoleType();
	}
	
	@Override
	public List<Role> getRoleByRoleName(String roleName) {
		return roleDao.getRoleByRoleName(roleName);
	}
	
	@Override
	public List<Role> getRoleByRoleNameExcludeCurrentId(String roleName,Integer roleId){
		return roleDao.getRoleByRoleNameExcludeCurrentId(roleName,roleId);
	}
	
	@Override
	public PageBean queryForPageBySQL(String sql, Integer pageSize, Integer currentPage, Object... objs) {
		return roleDao.queryForPageBySQL(sql, pageSize, currentPage, objs);
	}
	
	@Override
	public PageBean queryForPageUseHQLByRoleName(String roleName,Integer pageSize, Integer currentPage) {
		String HQL = " from Role where roleName like ? or roleType like ? ";
		return roleDao.queryForPageByHQL(HQL, pageSize, currentPage,"%"+roleName+"%","%"+roleName+"%");
	}
	
	
	
	@SuppressWarnings("rawtypes")
	public PageBean queryForPageUseHQL(JSONObject requestJson,Integer pageSize, Integer currentPage){		
		String HQL = null;
        Iterator iterator = requestJson.keys();
        List<String> parameters = new ArrayList<String>();
		while(iterator.hasNext()){
			String key = (String) iterator.next();
			key = StringUtil.convertNullToEmptyString(key);
			String value = requestJson.getString(key);
			value = StringUtil.convertNullToEmptyString(value);
			if(!"".equals(value)){
				HQL = (HQL == null?"": HQL + " OR ") +  key + " like ? ";
				parameters.add("%"+value+"%");
			}
		}
		HQL = " from Role " + (HQL == null?"":" where " + HQL);
		PageBean pageBean = roleDao.queryForPageByHQL(HQL, pageSize, currentPage,parameters.toArray());
		return pageBean;
	}
	
	@Override
	public void deleteById(Integer id) {
		Role role = new Role();
		role.setId(id);
		roleDao.deleteRoleFunctionByRoleId(id);
		roleDao.delete(role);		
	}
	
	public int deleteRoleFunctionByRoleId(Integer roleId){
		return roleDao.deleteRoleFunctionByRoleId(roleId);
	}
}